<template>
  <div>
    <div style="padding: 10px 20px;">
      <t-button block theme="primary" variant="base" @click="handleClickAddEventsFun">添加事件</t-button>
    </div>

    <t-collapse borderless="true">
      <t-collapse-panel
        v-if="pen?.events"
        v-for="(event, index) in pen.events"
        :key="event"
        :value="index"
        :header="'事件'+(index+1)"
      >
      <template #headerRightContent>
        <icon name="delete-1" size="16px" :style="{ marginLeft: '8px' }" @click="handleClicDelEventsFun(index)" />
      </template>
      <t-form label-align="left">
        <t-form-item label="事件类型" name="name">
          <t-select
            v-model="event.name"
            :options="EventNameOptions"
            @change="changeValue('name', index)"
          >
          </t-select>
        </t-form-item>
        <t-form-item label="事件行为" name="action">
          <t-select
            v-model="event.action"
            :options="EventActionOptions"
            @change="changeValue('action', index)"
          >
          </t-select>
        </t-form-item>
        <t-form-item :label="event.action === 5 ? 'Javascript' : '函数名称'" name="value">
          <template v-if="event.action === 5">
            <t-button shape="square" variant="outline" size="small" @click="handleClickJavaScriptFun('value', index)">
              <t-icon name="ellipsis" />
            </t-button>
          </template>
          <template v-else>
            <t-input v-model="event.value" @change="changeValue('value', index)" />
          </template>
        </t-form-item>
        <!-- <t-form-item label="触发条件" name="type"> -->
          <!-- <t-select -->
            <!-- v-model="event.where.type" -->
            <!-- :options="EventTriggerConditionOptions" -->
            <!-- @change="changeValue('type', index, 'where')" -->
          <!-- > -->
          <!-- </t-select> -->
        <!-- </t-form-item> -->
      </t-form>
      </t-collapse-panel>
    </t-collapse>
    <t-dialog
      header="JavaScript"
      :visible.sync="visible"
      @confirm="onConfirm"
      width="60%"
      :confirmOnEnter="true"
      :onClose="close"
      dialogClassName="dialogClass"
    >
    <div slot="body">
      <div style="width: 100%;height: 50vh;">
        <Editor :editorDefaultVal="editorDefaultVal" @updateEventVal="updateEventVal" />
      </div>
      <div>可获取pen、params和context参数</div>
    </div>
    </t-dialog>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, ref, watch } from 'vue';
// import { Event } from '@meta2d/core';
import { EventNameOptions, EventActionOptions, EventTriggerConditionOptions } from "../../../utils/dataAtRest";
import { useSelection } from '../../../services/selections';
import Editor from '../../../views/Editor.vue';
import { Pen } from '@meta2d/core';

const { selections } = useSelection();
const pen = ref<any>();
const rect = ref<any>();
const eventIdex = ref<number>(-1);
const visible = ref<boolean>(false);
const editorDefaultVal = ref<any>();
onMounted(() => {
  console.log('selections.pen', selections.pen)
  getPen();
});

const getPen = () => {
  // if (selections.pen && selections.pen.length > 0) {
  //   pen.value = selections.pen[0];
  //   if (pen.value.globalAlpha == undefined) {
  //     pen.value.globalAlpha = 1;
  //   }
  //   rect.value = meta2d.getPenRect(pen.value);
  // } else {
  //   console.error('No pen data available');
  // }
  pen.value = selections.pen;
  if (!pen.value["globalAlpha"]) {
    pen.value["globalAlpha"] = 1;
  }
  rect.value = meta2d.getPenRect(pen.value);
};

// const watcher = watch(() => (selections.pen as Pen[])[0].id, getPen, {
//   deep: true,
//   immediate: true
// });
const watcher = watch(() => {
  if (selections.pen) {
    selections.pen.id;
  }
}, getPen);

watch(
  () => selections.pen,
  (newVal: any) => {
    if (newVal) {
      getPen();
    }
  },
  { immediate: true }
);

const changeValue = (prop: string, index:number, where?: string) => {
  const v: any = { id: pen.value.id };
  // console.log('pen.value=====', pen.value)
  if(where === undefined) {
    let propertyPath = `events.${index}.${prop}`;
    v[propertyPath] = pen.value.events[index][prop];
    meta2d.setValue(v, { render: true });
  } else {
    let propertyPath = `events.${index}.where.${prop}`;
    v[propertyPath] = pen.value.events[index].where[prop];
    meta2d.setValue(v, { render: true });
  }
};


onUnmounted(() => {
  watcher();
});

const handleClickAddEventsFun = () => {
  console.log(' pen.value.events',  pen.value.events)
  if(pen.value.events === undefined) {
    console.log('aaaaaaa')
    pen.value.events = [];
  }
  pen.value.events.push({
    where: {
      type: null
    }
  })
}

const handleClicDelEventsFun = (index:number) => {
  console.log('pen.value.events', pen.value.events)
}

const handleClickJavaScriptFun = (prop: string, index:number) => {
  eventIdex.value = index;
  editorDefaultVal.value = pen.value.events[index][prop];
  visible.value = true;
}
const updateEventVal = (val: any) => {
  // pen.value.events[eventIdex.value]['value'] = val;
  editorDefaultVal.value = val
}
const onConfirm = () => {
  const v: any = { id: pen.value.id };
  let propertyPath = `events.${eventIdex.value}.value`;
  pen.value.events[eventIdex.value]['value'] = editorDefaultVal.value;
  console.log('__________', pen.value.events[eventIdex.value]['value'])
  v[propertyPath] = pen.value.events[eventIdex.value]['value'];
  meta2d.setValue(v, { render: true });
  visible.value = false;
}
const close = () => {
  visible.value = false;
}

globalThis.demoFun = (pen:any,params:any) => {
  console.log('当前图元：',pen,'参数：',params);
}
// globalThis.le5leFn= (pen,params) =>{
//   
// };
</script>

<style lang="scss" scoped>
  :deep(.t-form) {
    .t-form__item {
      margin-bottom: 8px;
    }
    .t-form__label {
      padding-right: 8px;
      label {
        font-size: 12px;
        font-weight: 400;
        color: #7f838c;
        line-height: 18px;
        letter-spacing: 0px;
      }
    }

    .t-divider {
      margin: 12px 0;
    }

    .t-input--auto-width {
      width: 100%;
    }
  }
  :deep(.t-collapse-panel__wrapper) {
    border-bottom: solid 1px var(--td-component-border);
    .t-collapse-panel__content {
      padding: 8px 12px;
    }
  }
  .dialogClass {
    margin: 20px;
  }
</style>